package net.wapproject.utils;

import java.awt.Image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;

import javax.swing.ImageIcon;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiWriter;
import com.sun.jimi.core.options.JPGOptions;

/**
 * 
 * @author HoangAnh
 *
 */
public class ImageResize {
	private static final Logger logger = Logger.getLogger(ImageResize.class);
	public static final int[] IMAGES_WIDTH = {40, 80, 120, 200};
	public static final int[] IMAGES_HEIGHT = {40, 80, 120, 200};
	public static final int newW = 700;
	public static final int newH = 800;
	
	
	public static int[] calculateNewSize(int orgWidth, int orgHeight, int screenWidth, int screenHeight) {
		if (orgWidth <= screenWidth && orgHeight <= screenHeight) {
			return new int[] {orgWidth, orgHeight};
		}
	    double newRatio = (double)screenWidth / (double)screenHeight;
	    double imageRatio = (double)orgWidth / (double)orgHeight;
	    if (newRatio < imageRatio) {
	      screenHeight = (int)(screenWidth / imageRatio);
	    } else {
	      screenWidth = (int)(screenHeight * imageRatio);
	    }
	    int[] newSize = new int[2];
	    newSize[0] = screenWidth;
	    newSize[1] = screenHeight;
	    return newSize;
	}	
	
	public static byte[] resizeImage(byte[] imagedata, int newWidth, int newHeight) {
		Image image = new ImageIcon(imagedata).getImage();
		int orgWidth = image.getWidth(null);
		int orgHeight = image.getHeight(null);
		if (orgWidth <= newWidth && orgHeight <= newHeight) {
			return imagedata;
		}
		int newSize[] = calculateNewSize(orgWidth, orgHeight, newWidth, newHeight);
		
		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();
			
			Image img = image.getScaledInstance(newSize[0], newSize[1], Image.SCALE_SMOOTH);
			JimiWriter jimiWriter = Jimi.createJimiWriter("image/jpeg", out);
			JPGOptions options = new JPGOptions();
			options.setQuality(100);
			jimiWriter.setOptions(options);
			jimiWriter.setSource(img);
			jimiWriter.putImage(out);
			out.flush();
			return out.toByteArray();
		} catch (Throwable t) {
			t.printStackTrace();
			return imagedata;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception ignore) {}
			}
		}
	}
	
	public static int[] save(File file, String url) {
		final String location = "save() - ";
		logger.debug(location + "BEGIN");
		
		int[] size = new int[2];
		try {
			byte[] data = FileUtils.readFileToByteArray(file);
			byte[] resizedData = resizeImage(data, newW, newH);
			String diskUrl = ConfigurationUtils.get(ConfigurationUtils.KEY_SOURCE_FOLDER);
        	String path = diskUrl + url;
        	System.out.println(path);
			FileUtils.writeByteArrayToFile(new File(path), resizedData);
			Image image = new ImageIcon(resizedData).getImage();
        	size[0] = image.getWidth(null);
        	size[1] = image.getHeight(null);
		} catch (Exception e) {
			logger.error(location, e);
			size[0] = 700;
			size[1] = 800;
		}

		logger.debug(location + "END");
		return size;
	}
	
	/**
	 * The method resize with array contains values of new image.
	 *
	 * @param file           .
	 */
	public static void resizeToSave(File file, String name) {
		final String location = "resize() - ";
		logger.debug(location + "BEGIN");
		
		try {
			byte[] data = FileUtils.readFileToByteArray(file);
			// save the orgirinal image to disk.
			String diskUrl = ConfigurationUtils.get(ConfigurationUtils.KEY_SOURCE_FOLDER);
//			diskUrl = "D:\\Users\\photo";
			
			FileUtils.writeByteArrayToFile(new File(diskUrl + "/" + name + ".jpg"), data);
			
			for (int i = 0; i < IMAGES_WIDTH.length; i++) {
				int newW = IMAGES_WIDTH[i];
				int newH = IMAGES_HEIGHT[i];
				byte[] resizedData = resizeImage(data, newW, newH);
				FileUtils.writeByteArrayToFile(new File(diskUrl + "/" + name + "_" + newW + "_" + newH + ".jpg"), resizedData);
			} // end for.
			
			logger.debug(location + "END");
		} catch (Exception e) {
			logger.error(location, e);
		}
	} // end method.
	
	/**
	 * The method to save image to disk.
	 *
	 * @param link
	 * @return           .
	 */
	public static byte[] save(String link){
		try {
		    
            link = link.replace(" ", "%20");
            URL url = new URL(link);
			InputStream in = url.openStream();
			byte[] data = IOUtils.toByteArray(in);
			
         return data;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}

	
	public void resize(String urlImage) {
		try {
			byte[] data = FileUtils.readFileToByteArray(new File(new URI(urlImage)));
				byte[] resizedData = resizeImage(data,  IMAGES_WIDTH[0],IMAGES_HEIGHT[0]);
				FileUtils.writeByteArrayToFile(new File("D:\\a.jpg"), resizedData);				
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void resize(byte[] data) {
		try {
				byte[] resizedData = resizeImage(data,  200,50);
				FileUtils.writeByteArrayToFile(new File("D:\\a.jpg"), resizedData);				
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws IOException {
//		ImageResize imageResize = new ImageResize();
//		String link = "http://www.google.com.vn/logos/2011/earthday11_sr.jpg";
//		byte[] data = save(link);
		
//		byte[] data = FileUtils.readFileToByteArray(new File("E:\\Foto\\Picture\\vui ve\\1.jpg"));
		
//		imageResize.save(data, "");
		
	}
	
}
